package com.hyy.book2.config;

import com.hyy.book2.model.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.resource.NoResourceFoundException;


//统一异常处理
@ControllerAdvice
@Slf4j
@ResponseBody
public class ExceptionAdvice {

    @ExceptionHandler
    public Object handle(Exception e) {
        log.error("发生异常：{}",e.getMessage());
        return Result.fail();
    }

    //    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//这个注解可以修改响应的状态码
    @ExceptionHandler
    public Object handle(ArrayIndexOutOfBoundsException e) {
        log.error("发生异常：{}", e.getMessage());
        return Result.fail("数组越界异常");
    }


    @ExceptionHandler
    public Object handle(NullPointerException e) {
        log.error("发生异常：{}", e.getMessage());
        return Result.fail("空指针");
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler
    public Object handel(NoResourceFoundException e){
        log.error("发生异常,e{}",e.getResourcePath());
        return Result.fail("发生NoResourceFoundException异常，路径："+e.getMessage());
    }

}
